<template>
  <div>
    <!-- 页面标题和报表控制 -->
    <v-row class="mb-6">
      <v-col cols="12">
        <!-- 移动端垂直布局，桌面端水平布局 -->
        <div class="d-flex flex-column flex-md-row justify-end align-center ga-3">
          <!-- 仪表盘日期 -->
          <v-text-field
            v-model="selectedDate"
            type="date"
            :label="$t('dashboard.dashboardDate')"
            prepend-inner-icon="mdi-calendar"
            variant="outlined"
            density="compact"
            class="date-field"
            @update:model-value="onDateChange"
          ></v-text-field>
          
          <!-- 报表开始日期 -->
          <v-text-field
            v-model="startDate"
            type="date"
            :label="$t('dashboard.startDate')"
            prepend-inner-icon="mdi-calendar-start"
            variant="outlined"
            density="compact"
            class="date-field"
          ></v-text-field>
          
          <!-- 报表结束日期 -->
          <v-text-field
            v-model="endDate"
            type="date"
            :label="$t('dashboard.endDate')"
            prepend-inner-icon="mdi-calendar-end"
            variant="outlined"
            density="compact"
            class="date-field"
          ></v-text-field>
          
          <!-- 生成报表按钮 -->
          <v-btn
            color="primary"
            prepend-icon="mdi-file-download"
            @click="generateReport"
            :loading="reportLoading"
            class="report-btn"
          >
            {{ $t('dashboard.generateReport') }}
          </v-btn>
        </div>
      </v-col>
    </v-row>

    <!-- 统计卡片 -->
    <v-row class="mb-6">
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.totalStudents')"
          :value="studentsStore.statistics.totalStudents"
          icon="mdi-account-group"
          color="primary"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.presentToday')"
          :value="studentsStore.statistics.arrivedStudents"
          icon="mdi-check-circle"
          color="success"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.onLeave')"
          :value="studentsStore.students.filter(s => s.arrival_status === 'leave').length"
          icon="mdi-calendar-remove"
          color="warning"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.abnormal')"
          :value="studentsStore.statistics.overdueArrivals"
          icon="mdi-alert-circle"
          color="error"
          :clickable="hasAbnormalStudents"
          @click="hasAbnormalStudents && openAbnormalDialog()"
        />
      </v-col>
    </v-row>

      <!-- 离园方式统计 -->


    <!-- 班级出勤情况 -->
    <v-row class="mb-6">
      <v-col cols="12">
        <v-card>
          <v-card-title>{{ $t('dashboard.classAttendance') }}</v-card-title>
          <v-card-text>
            <v-data-table
              :headers="classHeaders"
              :items="studentsStore.getAllClassesAttendance"
              :loading="loading"
              class="elevation-1"
              :no-data-text="t('common.noData')"
            >
              <template v-slot:item.attendance_rate="{ item }">
                <v-chip
                  :color="getAttendanceColor(item.attendance_rate)"
                  variant="elevated"
                  size="small"
                >
                  {{ item.attendance_rate }}%
                </v-chip>
              </template>
              
              <template v-slot:item.actions="{ item }">
                <v-btn
                  color="primary"
                  variant="outlined"
                  size="small"
                  @click="openDetailReport(item)"
                >
                  {{ $t('dashboard.viewDetail') }}
                </v-btn>
              </template>
              
              <template v-slot:item.status_breakdown="{ item }">
                <div class="d-flex gap-2">
                  <v-chip color="green" size="x-small">{{ item.present_count }}</v-chip>
                  <v-chip color="orange" size="x-small">{{ item.leave_count }}</v-chip>
                  <v-chip color="red" size="x-small">{{ item.abnormal_count }}</v-chip>
                </div>
              </template>
            </v-data-table>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- 异常学生信息 -->
    <v-row v-if="hasAbnormalStudents">
      <v-col cols="12" md="6">
        <v-card>
          <v-card-title class="text-error">
            <v-icon class="me-2">mdi-alert-circle</v-icon>
            {{ $t('dashboard.arrivalAbnormalStudents') }}
          </v-card-title>
          <v-card-text>
            <v-list density="compact">
              <v-list-item
                v-for="student in statistics?.abnormal?.arrival || []"
                :key="student.id"
                class="px-0"
              >
                <template v-slot:prepend>
                  <v-avatar size="32" color="red">
                    <span class="text-white text-caption">{{ student.name.charAt(0) }}</span>
                  </v-avatar>
                </template>
                
                <v-list-item-title>{{ student.name }} ({{ student.student_no }})</v-list-item-title>
                <v-list-item-subtitle>
                  {{ student.class_name }} - {{ student.notes }}
                </v-list-item-subtitle>
              </v-list-item>
            </v-list>
          </v-card-text>
        </v-card>
      </v-col>
      
      <v-col cols="12" md="6">
        <v-card>
          <v-card-title class="text-error">
            <v-icon class="me-2">mdi-alert-circle</v-icon>
            {{ $t('dashboard.departureAbnormalStudents') }}
          </v-card-title>
          <v-card-text>
            <v-list density="compact">
              <v-list-item
                v-for="student in statistics?.abnormal?.departure || []"
                :key="student.id"
                class="px-0"
              >
                <template v-slot:prepend>
                  <v-avatar size="32" color="red">
                    <span class="text-white text-caption">{{ student.name.charAt(0) }}</span>
                  </v-avatar>
                </template>
                
                <v-list-item-title>{{ student.name }} ({{ student.student_no }})</v-list-item-title>
                <v-list-item-subtitle>
                  {{ student.class_name }} - {{ student.notes }}
                </v-list-item-subtitle>
              </v-list-item>
            </v-list>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- 详细报表弹窗 -->
    <v-dialog v-model="detailDialog" max-width="1200px" scrollable>
      <v-card>
        <v-card-title class="d-flex justify-space-between align-center">
          <span>{{ selectedClass?.class_name }} - {{ $t('dashboard.detailReport') }}</span>
          <v-btn icon="mdi-close" variant="text" @click="detailDialog = false"></v-btn>
        </v-card-title>
        
        <v-card-text>
          <v-data-table
            :headers="detailHeaders"
            :items="detailReportData"
            :loading="detailLoading"
            class="elevation-1"
            density="compact"
          >
            <template v-slot:item.arrival_status="{ item }">
              <v-chip
                :color="getStatusColor(item.arrival_status)"
                size="small"
                variant="elevated"
              >
                {{ getStatusText(item.arrival_status) }}
              </v-chip>
            </template>
            
            <template v-slot:item.departure_status="{ item }">
              <v-chip
                :color="getStatusColor(item.departure_status)"
                size="small"
                variant="elevated"
              >
                {{ getStatusText(item.departure_status) }}
              </v-chip>
            </template>
          </v-data-table>
        </v-card-text>
        
        <v-card-actions>
          <v-btn 
            color="success" 
            prepend-icon="mdi-download" 
            @click="downloadDetailReport"
            :loading="downloadLoading"
          >
            {{ $t('common.download') }}
          </v-btn>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="detailDialog = false">{{ $t('common.close') }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>


  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useStudentsStore } from '@/stores/students'
import { useExceptionsStore } from '@/stores/exceptions'
import { useSocketStore } from '@/stores/socket'
import StatCard from '@/components/StatCard.vue'
import * as XLSX from 'xlsx'
import api from '@/utils/api'

const { t } = useI18n()
const studentsStore = useStudentsStore()
const exceptionsStore = useExceptionsStore()
const socketStore = useSocketStore() 

// 响应式数据
const reportLoading = ref(false)
const startDate = ref(new Date().toISOString().split('T')[0])
const endDate = ref(new Date().toISOString().split('T')[0])

// 详细报表相关
const detailDialog = ref(false)
const detailLoading = ref(false)
const selectedClass = ref(null)
const detailReportData = ref([])
const downloadLoading = ref(false)

// 异常学生弹窗相关
const abnormalDialog = ref(false)
const abnormalStudents = computed(() => studentsStore.getOverdueArrivals)

// 表格标题
const classHeaders = [
  { title: '班级名称', key: 'class_name', sortable: true },
  { title: '年级', key: 'grade', sortable: true },
  { title: '学生人数', key: 'total_students', sortable: true },
  { title: '出勤率', key: 'attendance_rate', sortable: true },
  { title: '班主任', key: 'head_teacher', sortable: true },
  { title: '详细报表', key: 'actions', sortable: false }
]

// 详细报表表格标题
const detailHeaders = [
  { title: t('student.studentNo'), key: 'student_no', sortable: true },
  { title: t('student.name'), key: 'name', sortable: true },
  { title: t('dashboard.arrivalStatus'), key: 'arrival_status', sortable: true },
  { title: t('dashboard.arrivalTime'), key: 'arrival_time', sortable: true },
  { title: t('dashboard.departureStatus'), key: 'departure_status', sortable: true },
  { title: t('dashboard.departureTime'), key: 'departure_time', sortable: true },
  { title: t('dashboard.notes'), key: 'notes', sortable: false }
]

// 计算属性
const selectedDate = computed({
  get: () => studentsStore.selectedDate,
  set: (value) => studentsStore.setSelectedDate(value)
})

const loading = computed(() => studentsStore.loading)
const statistics = computed(() => ({
  overall: {
    total_students: studentsStore.statistics.totalStudents,
    present_count: studentsStore.statistics.arrivedStudents,
    leave_count: studentsStore.students.filter(s => s.arrival_status === 'leave').length,
    abnormal_count: studentsStore.statistics.overdueArrivals
  },
  classes: studentsStore.getAllClassesAttendance
}))

const hasAbnormalStudents = computed(() => {
  return studentsStore.statistics.overdueArrivals > 0
})

// 方法
const loadDashboardData = async () => {
  try {
    // 并行加载数据以提高性能
    const [studentsResult, classesResult, dashboardResult] = await Promise.allSettled([
      studentsStore.fetchStudentsWithAttendance(),
      studentsStore.fetchClasses(),
      fetchDashboardStatistics() // 获取仪表盘统计数据
    ])
    
    // 检查加载结果
    if (studentsResult.status === 'rejected') {
      console.error('加载学生数据失败:', studentsResult.reason)
      window.showNotification?.('加载学生数据失败', 'warning')
    }
    
    if (classesResult.status === 'rejected') {
      console.error('加载班级数据失败:', classesResult.reason)
      window.showNotification?.('加载班级数据失败', 'warning')
    }
    
    if (dashboardResult.status === 'rejected') {
      console.error('加载仪表盘统计数据失败:', dashboardResult.reason)
      window.showNotification?.('加载仪表盘统计数据失败', 'warning')
    }
    
    // 执行异常检查
    try {
      await exceptionsStore.performExceptionCheck()
    } catch (exceptionError) {
      console.warn('异常检查失败:', exceptionError)
    }
    
    // 只有在至少一个数据源成功时才显示成功消息
    if (studentsResult.status === 'fulfilled' || classesResult.status === 'fulfilled' || dashboardResult.status === 'fulfilled') {
      window.showNotification?.(`已加载 ${studentsStore.selectedDate} 的考勤数据`, 'success')
    } else {
      window.showNotification?.('数据加载失败，请检查网络连接', 'error')
    }
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    window.showNotification?.('加载数据失败', 'error')
  }
}

// 获取仪表盘统计数据
const fetchDashboardStatistics = async () => {
  try {
    const response = await api.get('/dashboard/statistics', {
      params: { date: studentsStore.selectedDate }
    })
    
    if (response.data.success) {
      // 更新班级出勤统计数据
      studentsStore.classesAttendance = response.data.data.classes || []
      
      // 更新总体统计数据
      const overall = response.data.data.overall || {}
      studentsStore.statistics = {
        totalStudents: overall.total_students || 0,
        arrivedStudents: overall.present_count || 0,
        overdueArrivals: overall.abnormal_count || 0
      }
      
      console.log('仪表盘统计数据加载成功:', response.data.data)
    } else {
      throw new Error(response.data.message || '获取仪表盘统计数据失败')
    }
  } catch (error) {
    console.error('获取仪表盘统计数据失败:', error)
    throw error
  }
}

const onDateChange = async (newDate) => {
  console.log('日期变更:', newDate)
  studentsStore.setSelectedDate(newDate)
  
  // 重新加载数据
  await loadDashboardData()
}

// 打开异常学生弹窗
const openAbnormalDialog = () => {
  abnormalDialog.value = true
}

const generateReport = async () => {
  reportLoading.value = true
  try {
    const response = await api.get('/dashboard/class-attendance-report', {
      params: {
        start_date: startDate.value,
        end_date: endDate.value
      }
    })
    
    const reportData = response.data.data
    
    // 生成XLSX内容
    const xlsxData = generateClassSummaryXLSX(reportData)
    
    // 下载XLSX文件
    const fileName = `班级出勤汇总_${startDate.value}_${endDate.value}.xlsx`
    downloadXLSX(xlsxData, fileName)
    
    window.showNotification?.('报表生成成功', 'success')
  } catch (error) {
    console.error('生成报表失败:', error)
    window.showNotification?.('生成报表失败', 'error')
  } finally {
    reportLoading.value = false
  }
}

// 生成班级出勤汇总XLSX
const generateClassSummaryXLSX = (data) => {
  // 数据验证
  if (!data || !data.dailyReports || !Array.isArray(data.dailyReports)) {
    console.error('生成XLSX失败: 数据格式不正确', data)
    throw new Error('数据格式不正确，无法生成报表')
  }
  
  const headers = ['班级', '年级', '总学生数', '出勤人数', '请假人数', '异常人数', '未到人数', '出勤率(%)']
  
  // 添加日期范围信息
  const dateInfo = data.isDateRange 
    ? `报表日期范围: ${data.startDate} 至 ${data.endDate}`
    : `报表日期: ${data.startDate}`
  
  const xlsxRows = [
    [dateInfo],
    []
  ]
  
  // 为每一天生成独立的报表
  data.dailyReports.forEach((dailyReport, index) => {
    // 添加日期标题
    xlsxRows.push([`报表日期: ${dailyReport.date}`])
    xlsxRows.push([])
    xlsxRows.push(['班级出勤统计'])
    xlsxRows.push([])
    xlsxRows.push(headers)
    
    // 添加当日全校汇总行
    if (dailyReport.summary) {
      const summaryRow = [
        '全校汇总',
        '-',
        dailyReport.summary.total_students || 0,
        dailyReport.summary.present_count || 0,
        dailyReport.summary.leave_count || 0,
        dailyReport.summary.abnormal_count || 0,
        dailyReport.summary.not_arrived_count || 0,
        dailyReport.summary.attendance_rate || 0
      ]
      xlsxRows.push(summaryRow)
      xlsxRows.push([])
    }
    
    // 添加当日各班级数据
    if (dailyReport.classes && Array.isArray(dailyReport.classes)) {
      const classRows = dailyReport.classes.map(row => [
        row.class_name || '',
        row.grade || '',
        row.total_students || 0,
        row.present_count || 0,
        row.leave_count || 0,
        row.abnormal_count || 0,
        row.not_arrived_count || 0,
        row.attendance_rate || 0
      ])
      xlsxRows.push(...classRows)
    }
    
    // 如果不是最后一天，添加分隔行
    if (index < data.dailyReports.length - 1) {
      xlsxRows.push([])
      xlsxRows.push([])
    }
  })
  
  return xlsxRows
}

const downloadXLSX = (data, filename) => {
  const ws = XLSX.utils.aoa_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '班级出勤汇总')
  XLSX.writeFile(wb, filename)
}

const getAttendanceColor = (rate) => {
  if (rate >= 90) return 'green'
  if (rate >= 70) return 'orange'
  return 'red'
}

// 打开详细报表
const openDetailReport = async (classItem) => {
  selectedClass.value = classItem
  detailDialog.value = true
  detailLoading.value = true
  
  try {
    // 使用正确的班级ID字段名：id（而不是class_id）
    const response = await studentsStore.fetchClassAttendanceDetail(classItem.id, studentsStore.selectedDate)
    // 根据后端API返回的数据结构，学生数据在response.data.students中
    detailReportData.value = response.data?.students || []
    console.log('详细报表数据:', detailReportData.value)
  } catch (error) {
    console.error('获取详细报表失败:', error)
    window.showNotification?.('获取详细报表失败', 'error')
    detailReportData.value = []
  } finally {
    detailLoading.value = false
  }
}

// 状态颜色映射
const getStatusColor = (status) => {
  const colorMap = {
    'present': 'green',
    'leave': 'orange', 
    'abnormal': 'red',
    'absent': 'grey',
    'not_left': 'blue',
    'bus': 'purple',
    'parent_pickup': 'teal',
    'after_school': 'indigo',
    'special_course': 'pink'
  }
  return colorMap[status] || 'grey'
}

// 状态文本映射
const getStatusText = (status) => {
  const textMap = {
    'present': '已到',
    'leave': '请假',
    'abnormal': '异常',
    'absent': '缺席',
    'not_left': '未离园',
    'bus': '校车接送',
    'parent_pickup': '家长接领',
    'after_school': '晚托班',
    'special_course': '特色课程'
  }
  return textMap[status] || status || '未记录'
}

// 下载详细报表
const downloadDetailReport = () => {
  if (!detailReportData.value || detailReportData.value.length === 0) {
    window.showNotification?.('暂无数据可下载', 'warning')
    return
  }
  
  downloadLoading.value = true
  
  try {
    // 构建XLSX内容
    const headers = [
      '学号',
      '姓名', 
      '入园状态',
      '入园时间',
      '离园状态',
      '离园时间',
      '备注'
    ]
    
    const xlsxRows = []
    xlsxRows.push(headers)
    
    // 添加学生数据
    detailReportData.value.forEach(student => {
      const row = [
        student.student_no || '',
        student.name || '',
        getStatusText(student.arrival_status) || '',
        student.arrival_time || '',
        getStatusText(student.departure_status) || '',
        student.departure_time || '',
        student.notes || ''
      ]
      xlsxRows.push(row)
    })
    
    // 生成文件名
    const className = selectedClass.value?.class_name || '班级'
    const date = selectedDate.value
    const filename = `${className}_详细报表_${date}.xlsx`
    
    // 使用XLSX下载文件
    const ws = XLSX.utils.aoa_to_sheet(xlsxRows)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '详细报表')
    XLSX.writeFile(wb, filename)
    
    window.showNotification?.('报表下载成功', 'success')
  } catch (error) {
    console.error('下载报表失败:', error)
    window.showNotification?.('下载报表失败', 'error')
  } finally {
    downloadLoading.value = false
  }
}

// 设置WebSocket事件监听器
const setupSocketListeners = () => {
  // 确保socket存在
  if (!socketStore.socket) {
    console.warn('Socket未初始化，无法设置监听器')
    return
  }
  
  // 重要：设置学生数据监听器，确保WebSocket重连后能正常接收数据
  studentsStore.initSocketListeners()
  
  // 监听学生状态更新，实时刷新仪表盘统计数据
  socketStore.socket.on('student-status-updated', async () => {
    console.log('接收到学生状态更新，刷新仪表盘统计数据')
    await fetchDashboardStatistics()
  })
  
  // 监听考勤数据更新
  socketStore.socket.on('attendance-updated', async () => {
    console.log('接收到考勤数据更新，刷新仪表盘统计数据')
    await fetchDashboardStatistics()
  })
}

// 监听WebSocket连接状态变化，重连后重新设置监听器
const setupConnectionWatcher = () => {
  if (socketStore.socket) {
    socketStore.socket.on('connect', () => {
      console.log('WebSocket重连成功，重新设置仪表盘事件监听器')
      setupSocketListeners()
      // 重连后重新加载数据
      loadDashboardData()
    })
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await loadDashboardData()
  
  // 设置WebSocket事件监听器
  setupSocketListeners()
  
  // 设置连接状态监听器，确保重连后重新设置事件监听器
  setupConnectionWatcher()
  
  // 启动实时更新
  studentsStore.startRealTimeUpdate()
  exceptionsStore.startRealTimeCheck()
})

// 页面卸载时清理
onUnmounted(() => {
  studentsStore.stopRealTimeUpdate()
  exceptionsStore.stopRealTimeCheck()
  
  // 清理WebSocket事件监听器
  if (socketStore.socket) {
    socketStore.socket.off('connect')
    socketStore.socket.off('student-status-updated')
    socketStore.socket.off('attendance-updated')
  }
})
</script>

<style scoped>
.v-card {
  transition: all 0.3s ease;
}

.v-card:hover {
  transform: translateY(-2px);
}

.text-error {
  color: rgb(var(--v-theme-error)) !important;
}

/* 响应式日期字段样式 */
.date-field {
  max-width: 200px;
  min-width: 160px;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .date-field {
    max-width: 100%;
    width: 100%;
    margin-bottom: 8px;
  }
  
  .report-btn {
    width: 100%;
    margin-top: 8px;
  }
  
  /* 移动端垂直布局间距调整 */
  .flex-column .date-field:last-of-type {
    margin-bottom: 16px;
  }
}

/* 桌面端优化 */
@media (min-width: 769px) {
  .date-field {
    flex: 0 0 auto;
  }
  
  .report-btn {
    flex: 0 0 auto;
    min-width: 140px;
  }
}
</style>
